package com.orcamento.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.orcamento.dao.EventDao;
import com.orcamento.entity.Account;
import com.orcamento.entity.Category;
import com.orcamento.entity.Event;
import com.orcamento.exception.NotFoundException;
import com.orcamento.exception.ServiceException;

public class EventService {

	@Autowired
	private transient EventDao eventDao;
	
	@Autowired
	private transient CategoryService categoryService;
	
	@Autowired
	private transient AccountService accountService;

	public void save(Event event, Long accountId) throws ServiceException {
		try {
			Account account = accountService.findById(accountId);
			event.setAccount(account);
			
			if( event.getCategory().getId() == null ) {
				event.setCategory(null);
			}
			
			event.setActive(true);
			eventDao.save(event);
		} catch (Exception e) {
			throw new ServiceException("Erro ao salvar evento.", e.getMessage());
		}
	}

	public List<Event> findAll(Long accountId) {
		return eventDao.findAllByAccount(accountId); 
	}

	public Event findById(Long id, Long accountId) throws NotFoundException {
		Event event = eventDao.findByIdAndAccount(id, accountId);
		if( event == null ) {
			throw new NotFoundException(id, "Event");
		}
		return event;
	}
	
	public void update(Event event, Long accountId) throws ServiceException {
		try {
			Event eventToUpdate = findById(event.getId(), accountId);
			eventToUpdate.setName( event.getName() );
			eventToUpdate.setDescription( event.getDescription() );
			eventToUpdate.setActive( event.getActive() );
			if( event.getCategory().getId() == null ) {
				eventToUpdate.setCategory(null);
			} else {
				Category category = new Category();
				category.setId(event.getCategory().getId());
				eventToUpdate.setCategory( category );
			}
			eventDao.save(eventToUpdate);
		} catch( Exception e ) {
			throw new ServiceException("Ocorreu um erro ao atualizar o Evento com id " + event.getId(),  e.getMessage());
		}
	}

}
